<?php

namespace Lib;

class Base {
    private static $appName = 'Web';
    protected static $apps = [
        'Web',
        'Wap',
        'Admin',
        'Api',
    ];

    function __construct() {

    }

    public static function run() {
        self::init();
    }

    /*
     * Init
     */
    public static function init() {
        header("Content-type: text/html; charset=utf-8");

        // Register autoload
        spl_autoload_register(function($class) {
            $classFile = ROOT_PATH . '/' . str_replace('\\', '/', $class) . '.class.php';
            if (is_file($classFile)) {
                require_once $classFile;
            }
        });

        // Error handle
        set_error_handler(array(__NAMESPACE__ . '\Base', 'errorHandler'));

        $sapiName = php_sapi_name();
        if (false !== strripos($sapiName, 'cli')) {
            self::cli();
        } else {
            self::router();
        }

    }

    /**
     * Router
     */
    public static function router() {
        $uri = $_SERVER['REQUEST_URI'];
        $uri = parse_url($uri, PHP_URL_PATH);
        $uri = explode('/', trim($uri, '/'));

        self::$appName = 'Web';
        if (in_array(ucfirst($uri[0]), self::$apps)) {
            self::$appName = $uri[0];
        }

        define('App_Name', self::$appName);

        $class  = !empty($uri[1]) ? ucfirst($uri[1]) : 'Index';
        $action = !empty($uri[2]) ? $uri[2] : 'index';

        $controllerPre = 'Controller_';
        $className     = '\App\\' . self::$appName . '\Controller\\' . $controllerPre . $class;

        if (!class_exists($className)) {
            echo $className . '类不存在';
            exit;
        }

        $obj    = new $className;
        $params = array_slice($uri, 2);

        call_user_func_array(array($obj, $action), $params);
    }

    /**
     * cli handler
     *
     * @demo php index.php Web/Test/execute a b
     */
    public static function cli() {
        global $argv;

        // 跳过队列监控
        if ($argv[0] == 'queueMonitor.php') {
            return true;
        }
        if (empty($argv[1])) {
            echo "执行的Cron文件不存在！";
            exit;
        }

        list($appName, $class, $action) = explode('/', trim($argv[1], '/'));

        define('App_Name', $appName);

        $className = '\App\\' . App_Name . '\Cron\\' . $class;

        if (!class_exists($className)) {
            echo $className . '类不存在';
            exit;
        }

        $obj    = new $className;
        $params = array_splice($argv, 2);

        call_user_func_array(array($obj, $action), $params);
    }


    /**
     * error handler
     */
    public static function errorHandler($errno, $errstr, $errfile, $errline) {
        $requesUri = '';
        if (isset($_SERVER['REQUEST_URI'])) {
            $requesUri = $_SERVER['REQUEST_URI'];
        }
        switch ($errno) {
            case E_NOTICE:
                $str = "{$requesUri} PHP Notice: {$errstr} {$errfile} on line {$errline}";
                break;
            case E_STRICT:
                break;
            case E_WARNING:
                $str = "{$requesUri} PHP Warning: {$errstr} {$errfile} on line {$errline}";
                break;
            case E_DEPRECATED:
                $str = "{$requesUri} Deprecated: {$errstr} {$errfile} on line {$errline}";
                break;
            default:
                $str = "{$requesUri}  [{$errno}] {$errstr} {$errfile} on line {$errline}";
                break;
        }
        !empty($str) && error_log('[' . date('d-M-Y H:i:s') . '] ' . $str . "\n", 3, '/logs/php/php_error');
    }
}